import { App, Button, DatePicker, Descriptions, Dropdown, Flex, Form, Input, InputNumber, Modal, Select, Space, Switch, Table, Tag, Upload } from "antd";
import { useContext, useEffect, useState } from "react";
import { useForm } from "antd/es/form/Form";
import Search from "antd/es/input/Search";
import { project_api } from "../api/projects";
import { provider_api } from "../api/providers";
import { contract_api } from "../api/conracts";
import dayjs from "dayjs";
import { UploadOutlined } from "@ant-design/icons";
import { api_urls } from "../api/urls";
import storage from "../storage";
import { Global } from "../main";
import { USER_ROLE } from "../api/users";
import { invoice_api } from "../api/invoice";



export function Invoice() {
    const [searchLoading, setSearchLoading] = useState(false)
    const [invoicePage, setInvoicePage] = useState({ total: 0, content: [] })
    const [invoiceReq, setInvoiceReq] = useState({ page: 1, size: 15, project_id: -1, provider_id: -1, contract_id: -1 })
    const [updateInvoiceModalOpen, setInvoiceProjectModalOpen] = useState(false)
    const [createInvoiceModalOpen, setCreateInvoiceModalOpen] = useState(false)
    const [createInvoiceForm] = useForm();
    const [updateInvoiceForm] = useForm();
    const { message, modal } = App.useApp();
    const [currentInvoice, setCurrentInvoice] = useState({ special: false, invoice: true });

    const [allProjects, setAllProjects] = useState([]);
    const [allProviders, setAllProviders] = useState([]);
    const [allContracts, setAllContracts] = useState([]);

    const [projects, setProjects] = useState([]);
    const [providers, setProviders] = useState([]);
    const [contracts, setContracts] = useState([]);
    const [contractsForAdd, setcontractsForAdd] = useState([]);
    const [selectedProject, setSelectedProject] = useState(-1);
    const [selectedProvider, setSelectedProvider] = useState(-1);
    const [selectedContract, setSelectedContract] = useState(-1);

    const { role } = useContext(Global)

    const columns = [
        {
            title: '项目',
            dataIndex: 'project_name',
            key: 'project_name',
        },
        {
            title: '供应商',
            dataIndex: 'provider_name',
            key: 'provider_name',
        },
        {
            title: '合同编号',
            dataIndex: 'contract_no',
            key: 'contract_no',
        },

        {
            title: '开票日期',
            key: 'invoice_date',
            render: (_, row) => (
                row.invoice_date ? dayjs(row.invoice_date).format("YYYY-MM-DD") : ''
            )
        },
        {
            title: '开票金额',
            key: 'amount',
            render: (_, row) => (<>
                {row.amount ? `${row.amount}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',') : ''}
            </>)
        },
        {
            title: '备注',
            key: 'remarks',
            dataIndex: 'remarks',
        },
        {
            title: '操作',
            key: 'action',
            fixed: 'right',
            width: 150,
            render: (_, row) => (<Space size={'middle'}>
                <Button type="link" onClick={() => {
                    let theRow = { ...row, contract_no: row.contract_id, invoice_date: dayjs(row.invoice_date) };
                    console.log('the row', theRow)
                    setCurrentInvoice(theRow);
                    updateInvoiceForm.setFieldsValue(theRow);

                    setInvoiceProjectModalOpen(true)
                }} disabled={role === USER_ROLE.READONLY}>编辑</Button>
                <Button type="link" danger onClick={() => {
                    modal.confirm({
                        title: "删除发票",
                        content: `确认要删除发票吗？`,
                        onOk: () => {
                            invoice_api.deleteInvoice(row.id).then(() => {
                                reFreshInvoice();
                            }).catch(e => message.error(e))
                        },
                        okText: '确定',
                        cancelText: '取消'
                    })
                }} disabled={role === USER_ROLE.READONLY}>删除</Button>
            </Space>)
        },
    ];
    const reFreshInvoice = (ur) => {
        let request = invoiceReq;
        if (!!ur) {
            request = ur;
        }
        invoice_api.pageInvoice(request).then(data => {
            setInvoicePage(data)
            setSearchLoading(false)
        }).catch(e => message.error(e))
    }

    useEffect(() => {
        project_api.pageProject({ keyword: '', page: 1, size: -1 }).then(projects => {
            setAllProjects(projects.content.map(it => ({ label: it.name, value: it.id })))
            setProjects(projects.content.map(it => ({ label: it.name, value: it.id })))
        }).catch(e => message.error(e));
        provider_api.pageProvider({ keyword: '', page: 1, size: -1 }).then(providers => {
            setProviders(providers.content.map(it => ({ label: it.name, value: it.id })))
            setAllProviders(providers.content.map(it => ({ label: it.name, value: it.id })))
        }).catch(e => message.error(e));
        contract_api.pageContract({ keyword: '', page: 1, size: -1, project_id: -1, provider_id: -1 }).then(contracts => {
            setAllContracts(contracts.content.map(it => ({ label: it.no, value: it.id })))
            setContracts(contracts.content.map(it => ({ label: it.no, value: it.id })))
            setcontractsForAdd(contracts.content.map(it => ({ label: it.no, value: it.id })))
        })
        reFreshInvoice()
    }, []);
    return <>
        <Space style={{ margin: '10px' }}>
            <Select size="large" style={{ width: '15vw' }} value={selectedProject} defaultValue={-1}
                showSearch
                title="选择项目" filterOption={
                    (input, option) => {
                        return (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                    }
                } options={[{ value: -1, label: '所有项目' }, ...projects]}
                onChange={(value) => {
                    setSelectedProject(value)
                    reFreshInvoice({ ...invoiceReq, project_id: value, provider_id: selectedProvider, contract_id: selectedContract })
                }}></Select>
            <Select size="large" style={{ width: '15vw' }} value={selectedProvider} defaultValue={-1}
                showSearch
                filterOption={
                    (input, option) => {
                        return (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                    }
                }
                title="选择供应商" options={[{ value: -1, label: '所有供应商' }, ...providers]}
                onChange={(value) => {
                    setSelectedProvider(value)
                    reFreshInvoice({ ...invoiceReq, project_id: selectedProject, provider_id: value, contract_id: selectedContract })
                }}></Select>
            <Select size="large" style={{ width: '15vw' }} value={selectedContract} defaultValue={-1}
                showSearch
                filterOption={
                    (input, option) => {
                        return (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                    }
                }
                title="选择合同" options={[{ value: -1, label: '所有合同' }, ...contracts]}
                onChange={(value) => {
                    setSelectedContract(value)
                    reFreshInvoice({ ...invoiceReq, project_id: selectedProject, provider_id: selectedProvider, contract_id: value })
                }}></Select>
            <Button size="large" type="primary" onClick={() => {
                setCurrentInvoice({ special: false, invoice: true })
                createInvoiceForm.setFieldsValue({ special: false, invoice: true })
                createInvoiceForm.resetFields();
                setCreateInvoiceModalOpen(true)
            }} disabled={role === USER_ROLE.READONLY}>创建</Button>
        </Space>
        <Table size="small" pagination={{
            position: ["bottomLeft"],
            pageSizeOptions: [invoiceReq.size],
            total: invoicePage.total,
            current: invoiceReq.page,
            pageSize: invoiceReq.size,
            onChange: (page, pageSize) => {
                setInvoiceReq({ ...invoiceReq, page: page, size: pageSize });
                reFreshInvoice({ ...invoiceReq, page: page, size: pageSize })

            }
        }} dataSource={invoicePage.content} columns={columns}></Table>
        <Modal maskClosable={false} title="编辑发票" okText="确定" cancelText="取消" onOk={() => {
            updateInvoiceForm.validateFields().then(data => {
                invoice_api.updateInvoice({ ...data, invoice_date: data.invoice_date.valueOf() }).then(() => {
                    reFreshInvoice();
                    setInvoiceProjectModalOpen(false)
                })
            });

        }} onCancel={() => setInvoiceProjectModalOpen(false)} open={updateInvoiceModalOpen}>
            <Form labelCol={{ span: 6 }} value={currentInvoice} wrapperCol={{ span: 18 }} form={updateInvoiceForm} initialValues={currentInvoice}>
                <Form.Item label="索引" name={"id"} hidden>
                    <Input />
                </Form.Item>
                <Form.Item label="合同编号" name={"contract_no"} rules={[{
                    required: true,
                    message: '请选择合同'
                }]}>
                    <Select disabled options={contractsForAdd} showSearch filterOption={(input, option) => {
                        return (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                    }}></Select>
                </Form.Item>
                <Form.Item label="开票日期" name={"invoice_date"} rules={[{ required: true }]}>
                    <DatePicker></DatePicker>
                </Form.Item>
                <Form.Item label="发票金额" name={"amount"} rules={[{ required: true }]}>
                    <InputNumber formatter={(value) => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                        parser={(value) => value.replace(/\$\s?|(,*)/g, '')} style={{ width: '100%' }} />
                </Form.Item>
                <Form.Item label="备注" name={"remarks"} rules={[{ max: 50 }]}>
                    <Input.TextArea></Input.TextArea>
                </Form.Item>
            </Form>
        </Modal>
        <Modal maskClosable={false} title="新建发票" okText="确定" cancelText="取消" onOk={() => {
            createInvoiceForm.validateFields().then(data => {
                invoice_api.createInvoice({ ...data, invoice_date: data.invoice_date.valueOf() }).then(() => {
                    reFreshInvoice();
                    setCreateInvoiceModalOpen(false)
                })
            });

        }} onCancel={() => setCreateInvoiceModalOpen(false)} open={createInvoiceModalOpen}>
            <Form labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} form={createInvoiceForm} initialValues={currentInvoice}>
                <Form.Item label="合同编号" name={"contract_no"} rules={[{
                    required: true,
                    message: '请选择合同'
                }]}>
                    <Select options={contractsForAdd} showSearch filterOption={(input, option) => {
                        return (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                    }}></Select>
                </Form.Item>
                <Form.Item label="开票日期" name={"invoice_date"} rules={[{ required: true }]}>
                    <DatePicker></DatePicker>
                </Form.Item>
                <Form.Item label="发票金额" name={"amount"} rules={[{ required: true }]}>
                    <InputNumber formatter={(value) => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                        parser={(value) => value.replace(/\$\s?|(,*)/g, '')} style={{ width: '100%' }} />
                </Form.Item>
                <Form.Item label="备注" name={"remarks"} rules={[{ max: 50 }]}>
                    <Input.TextArea></Input.TextArea>
                </Form.Item>
            </Form>
        </Modal>


    </>
}